import {
	defineStore
} from 'pinia';
import {
	toGetUnusedList,
	toAddUnused,
	toDeleteUnused,
	toGetUnusedListByUserId

} from "@/utils/request/unused.js"
import moment from "moment"
export const useUnusedStore = defineStore('unused', {
	state: () => {
		return {
			status: {
				code: "",
				msg: ""
			},
			deletedStatus: {
				code: "",
				msg: ""
			},
			unusedList: []

		};
	},
	// 也可以这样定义
	// state: () => ({ count: 0 })
	actions: {
		//获取用户所在的学校的闲置列表
		async getUnusedList(data) {
			this.unusedList = []
			try {
				const res = await toGetUnusedList(data);
				this.status.code = res.code
				this.status.msg = res.msg;
				if (res.code == "200") {
					res.data.forEach((p) => {
						p.addTime = moment(p.addTime).format("YYYY-MM-DD HH:mm:ss")
						if (p.status == "0") {
							p.status = "出闲置"
						} else {
							p.status = "购闲置"
						}
						if (p.imgSrc != null && p.imgSrc != "") {
							p.imgSrc = p.imgSrc.split(";")
						}
						this.unusedList.unshift(p)
					})
				} else {
					this.unusedList = []
				}
			} catch (err) {
				this.status.code = "405";
				this.status.msg = "网络不好，请稍后重试"
			}
		},

		//发布闲置
		async addUnused(files, data) {
			try {
				const res = await toAddUnused(files, data);
				this.status.code = res.code
				this.status.msg = res.msg;
			} catch (err) {
				this.status.code = "405"
				this.status.msg = "网络不好，请稍后重试";
			}
		},
		//删除我发布的闲置
		async deleteUnused(data) {
			try {
				const res = await toDeleteUnused(data);
				this.deletedStatus.code = res.code
				this.deletedStatus.msg = res.msg;
			} catch (err) {
				this.deletedStatus.code = "405"
				this.deletedStatus.msg = "网络不好，请稍后重试";
			}
		},
		//获取我的闲置的列表
		async getUnusedListByUserId(userId) {
			try {
				this.unusedList = []
				const res = await toGetUnusedListByUserId(userId);
				this.status.code = res.code
				this.status.msg = res.msg;
				if (res.code == "200") {
					res.data.forEach((p) => {
						p.addTime = moment(p.addTime).format("YYYY-MM-DD HH:mm:ss")
						if (p.status == "0") {
							p.status = "出闲置"
						} else {
							p.status = "购闲置"
						}
						if (p.imgSrc != null && p.imgSrc != "") {
							p.imgSrc = p.imgSrc.split(";")
						}
						this.unusedList.unshift(p)
					})
				}

			} catch (err) {
				this.status.code = "405"
				this.status.msg = "网络不好，请稍后重试";
			}
		}
	}
});